import React from "react";
import{
    Page,
    Form,
    FormCell,
    CellHeader,
    Label,
    CellBody,
    Input,
    ButtonArea,
    Button,
    Toast
} from 'react-weui'
import {NavComponent} from "../../components/navgation/NavComponent";
import {loginAction} from "../../actions/loginAction";

export class LoginView extends React.Component{

    constructor(props){
        super(props);

        this.state={
            username:'sdf',
            password:'',
            showToast: false,
            showLoading:false,
        }
    }

    getValue(e,type){
        const kv = {};
        kv[type] = e.target.value;
        this.setState(kv);
    }

    login(){

        const that = this;

        this.setState({showLoading:true});

        loginAction(this.state.username,this.state.password).then(function (res) {

            that.setState({showLoading:false});

            if(res.items.length === 1){

                that.setState({showToast:true});

                window.localStorage.setItem('user',JSON.stringify(res.items[0]));

                setTimeout(function () {
                    that.setState({showToast:false});
                    that.props.history.goBack();
                },3000)
            }
        },function () {

            that.setState({showLoading:false});
        });
    }

    render(){

        return <Page className="input" title="Input" subTitle="表单输入" transition={true}>

            <NavComponent title={"登录"} history={this.props.history}/>

            <Form>
                <FormCell>
                    <CellHeader>
                        <Label>用户名</Label>
                    </CellHeader>
                    <CellBody>
                        <Input onChange={(e)=>{this.getValue.bind(this)(e,'username')}} type="text" placeholder="请输入用户名"/>
                    </CellBody>
                </FormCell>
                <FormCell>
                    <CellHeader>
                        <Label>密码</Label>
                    </CellHeader>
                    <CellBody>
                        <Input onChange={(e)=>{this.getValue.bind(this)(e,'password')}}  type="password" placeholder="请输入密码"/>
                    </CellBody>
                </FormCell>
            </Form>
            <ButtonArea>
                <Button onClick={this.login.bind(this)}>
                    登录
                </Button>
            </ButtonArea>

            <Toast icon="success-no-circle" show={this.state.showToast}>登录成功</Toast>
            <Toast icon="loading" show={this.state.showLoading}>登录中...</Toast>

        </Page>

    }

}